package com.webcams.core.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;

import com.webcams.core.resorts.DownloadListener;

public class AsyncDownloadBitmap extends AsyncTask<String, Integer, Bitmap> {

	private DownloadListener listener;
	private ProgressDialog progress;

	public AsyncDownloadBitmap(DownloadListener listener) {
		this.listener = listener;
	}

	public Bitmap downloadBitmap(String fileUrl){

		Log.v("DEBUG", fileUrl);
		
		try {
			URL url = new URL(fileUrl);
			HttpURLConnection connection = (HttpURLConnection)url.openConnection();
			int length = connection.getContentLength();

			ByteArrayOutputStream output = new ByteArrayOutputStream();
			InputStream inputStream = connection.getInputStream();

			int totalSize = connection.getContentLength();
			long downloadedSize = 0;

			if(progress != null) {
				progress.setMax(totalSize);
			}
			
			byte[] buffer = new byte[1024];
			int bufferLength = 0;

			while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
				output.write(buffer, 0, bufferLength);
				downloadedSize += bufferLength;
				publishProgress((int)downloadedSize);
			}
			Bitmap tempBitmap = BitmapFactory.decodeByteArray(output.toByteArray(), 0, length);
			return tempBitmap; 

		} catch (IOException e) {
			Log.e("DEBUGTAG", "Remtoe Image Exception", e);
		}

		return null;

	}

	@Override
	protected Bitmap doInBackground(String... urls) {
		return downloadBitmap(urls[0]);
	}

	@Override
	protected void onProgressUpdate(Integer... _progress) {
		if(progress != null) {
			progress.setProgress(_progress[0]);
		}
	}
	
	protected void onPostExecute(Bitmap result) {
		if(progress != null) {
			progress.dismiss();
		}
		listener.imageFinishedLoad(result);
	}

	public void setProgressDialog(ProgressDialog progressDialog) {
		this.progress = progressDialog;
	}
}
